<template>
	<view class="container">
		<view class="ui-all">
			<view class="avatar" @tap="handleUploadAvatar">
				<view class="imgAvatar">
					<view class="iavatar" :style="'background: url(' + profileEditDto.Avatar + ') no-repeat center/cover #eeeeee;'"></view>
				</view>
				<text>{{ $t('pages.sys.profile.changeAvatarText') }}</text>
				<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.userNameText') }}</text>
				<input type="text" v-model="profileEditDto.UserName" placeholder-class="place" :placeholder="$t('pages.sys.profile.userNamePlaceholder')" />
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.nickNameText') }}</text>
				<input type="text" v-model="profileEditDto.NickName" placeholder-class="place" :placeholder="$t('pages.sys.profile.nickNamePlaceholder')" />
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.emailText') }}</text>
				<input type="text" :disabled="true" v-model="profileEditDto.Email" />
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.mobileText') }}</text>
				<input type="number" :disabled="true" v-model="profileEditDto.PhoneNumber" />
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.genderText') }}</text>
				<picker @change="confirmGenderHandler" mode='selector' range-key="text" :value="genderIndex" :range="genders">
					<view class="picker">
						{{ genders[genderIndex].text }}
					</view>
				</picker>
				<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.birthdayText') }}</text>
				<picker @change="changeBirthdayHandler" mode="date" :value="formatToDate(profileEditDto.Birthday)">
					<view class="picker">
						{{ formatToDate(profileEditDto.Birthday) }}
					</view>
				</picker>
				<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.bloodTypeText') }}</text>
				<input type="text" v-model="profileEditDto.BloodType" placeholder-class="place" :placeholder="$t('pages.sys.profile.bloodTypePlaceholder')" />
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.addressText') }}</text>
				<textarea v-model="profileEditDto.Address" placeholder-class="place" :placeholder="$t('pages.sys.profile.addressPlaceholder')"></textarea>
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.profileText') }}</text>
				<textarea v-model="profileEditDto.Profile" placeholder-class="place" :placeholder="$t('pages.sys.profile.profilePlaceholder')"></textarea>
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.signatureText') }}</text>
				<textarea v-model="profileEditDto.Signature" placeholder-class="place" :placeholder="$t('pages.sys.profile.signaturePlaceholder')"></textarea>
			</view>
			<view class="ui-list">
				<text>{{ $t('pages.sys.profile.remarkText') }}</text>
				<textarea v-model="profileEditDto.Remark" placeholder-class="place" :placeholder="$t('pages.sys.profile.remarkPlaceholder')"></textarea>
			</view>
			
			<button class="button-submit" type="primary" @click="handleSubmit">{{ $t('common.submitText') }}</button>
		</view>
		
		<view>
			<!-- 提示信息弹窗 -->
			<uni-popup ref="message" type="message">
				<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
			</uni-popup>
		</view>
		
		<view style="margin-top: 80rpx;" />
	</view>
</template>

<script>
	import { getBase64 } from '@/utils/common';
	import { formatToDate } from '@/utils/date';
	import { pathToBase64 } from '@/utils/fileUtil';
	import { callFileBase64String } from '@/apis/file';
	import { profile } from '@/apis/identity';
	export default {
		data() {
			const that = this;
			return {
				profileEditDto: {
					/** 主键，唯一标识 */
					Id: -1,
					/** 用户名 */
					UserName: '',
					/** 用户昵称 */
					NickName: '',
					/** 电子邮箱 */
					Email: '',
					/** 手机号码 */
					PhoneNumber: '',
					/** 头像 */
					Avatar: null,
					
					/** 性别 */
					Gender: null,
					/** 生日 */
					Birthday: null,
					/** 血型 */
					BloodType: '',
					/** 标签 */
					Tag: null,
					/** 头衔 */
					Title: null,
					/** 地址 */
					Address: '',
					/** 简介 */
					Profile: '',
					/** 签名 */
					Signature: '',
					
					/** 备注 */
					Remark: '',
				},
				msgType: '',
				messageText: '',
				genderIndex: 0,
				genders: [{
					value: 0,
					text: that.$t('enum.gender.unknown')
				},{
					value: 1,
					text: that.$t('enum.gender.male')
				}, {
					value: 2,
					text: that.$t('enum.gender.female')
				}],
				formatToDate,
			}
		},
		async onShow() {
			const that = this;
			// 导航栏多语言
			uni.setNavigationBarTitle({
				title: that.$t('pages.sys.profile.modifyProfileText'),
			});
			try {
				uni.showLoading({
					title: that.$t('common.loadingText'),
					mask: true
				});
				
				// 用户信息
				const profileDto = await profile('modal');
				// console.log('onShow', profileDto);
				if(profileDto){
					that.profileEditDto = {
						/** 主键，唯一标识 */
						Id: profileDto.UserId,
						/** 用户名 */
						UserName: profileDto.UserName,
						/** 用户昵称 */
						NickName: profileDto.NickName,
						/** 电子邮箱 */
						Email: profileDto.Email,
						/** 手机号码 */
						PhoneNumber: profileDto.PhoneNumber,
						/** 头像 */
						Avatar: profileDto.Avatar,
						
						/** 性别 */
						Gender: profileDto.Gender,
						/** 生日 */
						Birthday: profileDto.Birthday,
						/** 血型 */
						BloodType: profileDto.BloodType,
						/** 标签 */
						Tag: profileDto.Tag,
						/** 头衔 */
						Title: profileDto.Title,
						/** 地址 */
						Address: profileDto.Address,
						/** 简介 */
						Profile: profileDto.Profile,
						/** 签名 */
						Signature: profileDto.Signature,
						
						/** 备注 */
						Remark: profileDto.Remark,
					}
				}
				// 用户性别
				// console.log('onShow', that.profileEditDto.Gender);
				for (let i = 0; i < that.genders.length; i++){
					if(that.genders[i].value === that.profileEditDto.Gender){
						that.genderIndex = i;
						// console.log('onShow_genderIndex', that.genderIndex);
						break;
					}
				}
				
				uni.hideLoading();
			}
			catch(err) {} 
			finally {
				uni.hideLoading();
			}
		},
		methods: {
			/** 处理上传头像 */
			handleUploadAvatar() {
				const that = this;
				uni.chooseImage({
					count: 1,	//最多可以选择的图片张数，默认9
					sizeType: ['original', 'compressed'],	//original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album', 'camera'],	//album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					crop: false,	//图像裁剪参数，设置后 sizeType 失效
					success: async function(res) {
						// console.log('handleUploadAvatar_success', res);
						if(res.tempFiles && res.tempFiles.length > 0){
							const tempFile = res.tempFiles[0];
							try {
								uni.showLoading({
									title: that.$t('common.loadingText'),
									mask: true
								});
								
								var pathToBase64String = await pathToBase64(tempFile.path);
								// console.log('pathToBase64', pathToBase64String);
								const dto = {
									Id: that.profileEditDto.Id,
									UserName: that.profileEditDto.UserName,
									NickName: that.profileEditDto.NickName,
									Email: that.profileEditDto.Email,
									PhoneNumber: that.profileEditDto.PhoneNumber,
									Avatar: pathToBase64String,
																		
									Gender: that.profileEditDto.Gender,
									Birthday: that.profileEditDto.Birthday,
									BloodType: that.profileEditDto.BloodType,
									Tag: that.profileEditDto.Tag,
									Title: that.profileEditDto.Title,
									Address: that.profileEditDto.Address,
									Profile: that.profileEditDto.Profile,
									Signature: that.profileEditDto.Signature,
																		
									Remark: that.profileEditDto.Remark,
								};
								
								// 方法1
								const userInfo = await that.$store.dispatch('profileEdit', { params: JSON.stringify(dto), mode: 'modal' });
								uni.hideLoading();
								if (userInfo !== undefined && userInfo !== null) {
									that.profileEditDto.Avatar = pathToBase64String;
									uni.showToast({
										title: that.$t('common.successText'),
										icon: 'success',
										duration: 2000
									});
								}
								
								// 方法2
								// if (typeof FileReader === "undefined") {
								// 	// console.log('不支持FileReader');
								// 	let base64Url = null;
								// 	const base64String = await callFileBase64String(tempFile.path);
								// 	// console.log('base64Url', base64String);
								// 	if (base64String) {
								// 		base64Url = `data:${tempFile.type};base64,${base64String}`
								// 	}
								// 	// console.log('base64Url', base64Url);
									
								// 	dto.Avatar = base64Url;
								// 	const userInfo = await that.$store.dispatch('profileEdit', { params: JSON.stringify(dto), mode: 'modal' });
								// 	uni.hideLoading();
								// 	if (userInfo !== undefined && userInfo !== null) {
								// 		that.profileEditDto.Avatar = res.Avatar;
								// 		uni.showToast({
								// 			title: that.$t('common.successText'),
								// 			icon: 'success',
								// 			duration: 2000
								// 		});
								// 	}
								// } else {
								// 	// console.log('支持FileReader');
								// 	// 下面的方法安卓5.1无效，估计是不支持 FileReader 对象
								// 	getBase64(tempFile, (base64Url) => {
								// 		// console.log('handleUploadAvatar_success', base64Url);
								// 		dto.Avatar = base64Url;
								// 		that.$store.dispatch('profileEdit', { params: JSON.stringify(dto), mode: 'modal' }).then((res) => {
								// 			uni.hideLoading();
								// 			if (res !== undefined && res !== null) {
								// 			  that.profileEditDto.Avatar = res.Avatar;
								// 			  uni.showToast({
								// 			  	title: that.$t('common.successText'),
								// 			  	icon: 'success',
								// 			  	duration: 2000
								// 			  });
								// 			}
								// 		});
								// 	});
								// }
							}
							catch(err) {} 
							finally {
								uni.hideLoading();
							}
						}
					}
				});
			},
			/** 确认性别选择 */
			confirmGenderHandler(e) {
				const that = this;
				// console.log('confirm', e);
				
				// <uni-data-picker> 控件用
				// if(e && e.detail && e.detail.value){
				// 	const selectedVal = e.detail.value[0];
				// 	if(selectedVal && selectedVal.value){
				// 		that.localeLang = selectedVal.value;
				// 		setLocalelang(that.localeLang);
				// 		that.$i18n.locale = that.localeLang;
				// 	}
				// }
				
				// <picker> 控件用
				if(e && e.detail){
					const selectedIndex = e.detail.value;
					// console.log('confirm', selectedIndex);
					if(selectedIndex >= 0){
						that.genderIndex = selectedIndex;
						that.profileEditDto.Gender = that.genders[that.genderIndex].value;
						// console.log('confirm', that.genderIndex);
					}
				}
			},
			/** 确认日期选择 */
			changeBirthdayHandler(e) {
				const that = this;
				// console.log('confirm', e);
				
				// <picker> 控件用
				if(e && e.detail){
					const selectedvalue = e.detail.value;
					// console.log('confirm', selectedvalue);
					if(selectedvalue){
						that.profileEditDto.Birthday = selectedvalue;
					}
				}
			},
			/** 处理提交 */
			async handleSubmit() {
				const that = this;
				if (that.profileEditDto.UserName === undefined || that.profileEditDto.UserName === null || that.profileEditDto.UserName === '') {
					that.msgType = 'warn';
					that.messageText = that.$t('pages.sys.profile.userNamePlaceholder');
					that.$refs.message.open();
					return;
				}
				if (that.profileEditDto.NickName === undefined || that.profileEditDto.NickName === null || that.profileEditDto.NickName === '') {
					that.msgType = 'warn';
					that.messageText = that.$t('pages.sys.profile.nickNamePlaceholder');
					that.$refs.message.open();
					return;
				}
				
				try {
					uni.showLoading({
						title: that.$t('common.loadingText'),
						mask: true
					});
					
					const dto = {
						Id: that.profileEditDto.Id,
						UserName: that.profileEditDto.UserName,
						NickName: that.profileEditDto.NickName,
						Email: that.profileEditDto.Email,
						PhoneNumber: that.profileEditDto.PhoneNumber,
						Avatar: that.profileEditDto.Avatar,
															
						Gender: that.profileEditDto.Gender,
						Birthday: that.profileEditDto.Birthday,
						BloodType: that.profileEditDto.BloodType,
						Tag: that.profileEditDto.Tag,
						Title: that.profileEditDto.Title,
						Address: that.profileEditDto.Address,
						Profile: that.profileEditDto.Profile,
						Signature: that.profileEditDto.Signature,
															
						Remark: that.profileEditDto.Remark,
					};
					// console.log('handleSubmit', dto);
					// console.log('handleSubmit', JSON.stringify(dto));
					const userInfo = await that.$store.dispatch('profileEdit', { params: JSON.stringify(dto), mode: 'modal' });
					if(userInfo === undefined || userInfo === null){
						uni.hideLoading();
						return;
					}
					
					that.profileEditDto = {
						/** 主键，唯一标识 */
						Id: userInfo.UserId,
						/** 用户名 */
						UserName: userInfo.UserName,
						/** 用户昵称 */
						NickName: userInfo.NickName,
						/** 电子邮箱 */
						Email: userInfo.Email,
						/** 手机号码 */
						PhoneNumber: userInfo.PhoneNumber,
						/** 头像 */
						Avatar: userInfo.Avatar,
						
						/** 性别 */
						Gender: userInfo.Gender,
						/** 生日 */
						Birthday: userInfo.Birthday,
						/** 血型 */
						BloodType: userInfo.BloodType,
						/** 标签 */
						Tag: userInfo.Tag,
						/** 头衔 */
						Title: userInfo.Title,
						/** 地址 */
						Address: userInfo.Address,
						/** 简介 */
						Profile: userInfo.Profile,
						/** 签名 */
						Signature: userInfo.Signature,
						
						/** 备注 */
						Remark: userInfo.Remark,
					}
					// 用户性别
					// console.log('onShow', that.profileEditDto.Gender);
					for (let i = 0; i < that.genders.length; i++){
						if(that.genders[i].value === that.profileEditDto.Gender){
							that.genderIndex = i;
							// console.log('onShow_genderIndex', that.genderIndex);
							break;
						}
					}
					
					uni.hideLoading();
					uni.showToast({
						icon: 'success',
						title: that.$t('common.successText'),
						mask: true
					});
					
					setTimeout(function () {
					    uni.navigateBack();
					}, 1500);
				}
				catch(err) {} 
				finally {
					uni.hideLoading();
				}
			}
		}
	}
</script>

<style lang="less">
	page {
		display: flex !important;
		align-items: center !important;  
		flex-direction: column !important;
		justify-content: center !important;
		background-color: #fff !important;
	}
	
	.container {
		width: 100vw;
	}

	.ui-all {
		padding: 20rpx 40rpx;
		
		.avatar {
			width: 100%;
			// text-align: left;
			// height: 140rpx;
			padding: 20rpx 0;
			border-bottom: 1px solid rgb(243,243,243);
			display: flex;
			align-items: center;
			
			text {
				width: 100%;
				display: inline-block;
				// vertical-align: middle;
				color: #8e8e93;
				font-size: 28rpx;
				margin-left: 40rpx;
			}
			
			.imgAvatar {
				flex-shrink:0;
				width: 140rpx;
				height: 140rpx;
				border-radius: 50%;
				display: inline-block;
				// vertical-align: middle;
				overflow: hidden;

				.iavatar {
					width: 100%;
					height: 100%;
					display: block;
				}
			}
			.to {
				flex-shrink: 0;
				// vertical-align: middle;
				width: 40upx;
				height: 40upx;
			}
		}
		.avatar:active {
		    background-color: #f8f8f8;
		}

		.ui-list {
			width: 100%;
			// text-align: left;
			// height: 140rpx;
			padding: 20rpx 0;
			border-bottom: 1px solid rgb(243,243,243);
			display: flex;
			align-items: center;
			
			text {
				display: inline-block;
				// vertical-align: middle;
				color: #4a4a4a;
				font-size: 28rpx;
				// margin-left: 40rpx;
				min-width: 150rpx;
			}
			input {
				// color: #030303;
				font-size: 30rpx;
				display: inline-block;
				// vertical-align: middle;
			}
			button{
				// color: #030303;
				font-size: 30rpx;
				display: inline-block;
				// vertical-align: middle;
				background: none;
				margin: 0;
				padding: 0;
				&::after{
					display: none;
				}
			}
			picker {
				width: 100%;
				// color: #030303;
				font-size: 30rpx;
				display: inline-block;
				// vertical-align: middle;
			}
			textarea {
				// color: #030303;
				font-size: 30rpx;
				// vertical-align: middle;
				height: 150rpx;
				width: 100%;
				// margin-top: 50rpx;
			}
			
			.place {
				// color: #999999;
				font-size: 28rpx;
			}
			.to {
				flex-shrink: 0;
				// vertical-align: middle;
				width: 40upx;
				height: 40upx;
			}
		}
		.ui-list:active {
		    background-color: #f8f8f8;
		}

		.button-submit {
			font-size: 35rpx;
			width: 500rpx;
			height: 100rpx;
			border-radius: 50rpx;
			line-height: 100rpx;
			text-align: center;
			margin-left: auto;
			margin-right: auto;
			margin-top: 35rpx;
		}
	}
</style>
